/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.tukano.odt;

import it.tukano.fun.Tuple2;
import it.tukano.lang.StringExt;
import it.tukano.swingdeco.containers.JPanelExt;
import it.tukano.swingdeco.controls.JComboBoxExt;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;

/**
 *
 * @author utente3
 */
public class OdtChoiceEditor extends OdtFieldEditor {

        /* default serial version code */
    private static final long serialVersionUID = 0;
    private final JComboBoxExt field;

    public OdtChoiceEditor(int size, String label, StringExt defaultValue) {
        String[] tokens = defaultValue.toString().split("#");
        field = new JComboBoxExt((Object[]) tokens);
        field.setEditable(true);
        setBorder(BorderFactory.createTitledBorder(label));
        add(new JPanelExt(new GridLayout(1, 1)).append(field));
    }

    @Override
    public void setValue(StringExt t) {
        if(!t.toString().contains("#")) field.setSelectedItem(t.toString());
    }

    @Override
    public Tuple2<StringExt, String> applyEditorValue(OdtField odtField, String xml) {
        StringExt s = new StringExt(field.getSelectedItem());
        return Tuple2.newInstance(s, xml);
    }

    @Override
    public void clearValue() {
        field.setSelectedIndex(0);
    }

    @Override
    public void onValueChange(final Runnable task) {
        field.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                task.run();
            }
        });
    }
}
